package com.aduerr.v1shouyin.mvp.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.entity.OrderRecordEntity;
import com.aduerr.v1shouyin.entity.OrderdetailEntity;
import com.aduerr.v1shouyin.entity.RefundMEntity;
import com.aduerr.v1shouyin.entity.TransactionFlowEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.view.RefoundMoneyDetailView;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.unioncard.BaseUnionActivity;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.BandOrUnbandGuidResultDialog;
import com.aduerr.v1shouyin.view.SecurityCodeView;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;

import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RefoundMoneyDetailActivity extends BaseUnionActivity implements RefoundMoneyDetailView {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_1)
    TextView tv1;
    @BindView(R.id.tv_redound_money)
    EditText tvRedoundMoney;
    @BindView(R.id.realymoney)
    TextView realymoney;
    @BindView(R.id.ordermoney)
    TextView ordermoney;
    @BindView(R.id.shopmoney)
    TextView shopmoney;
    @BindView(R.id.paytime)
    TextView paytime;
    @BindView(R.id.orderid)
    TextView orderid;
    @BindView(R.id.currentshop)
    TextView currentshop;
    @BindView(R.id.groupname)
    TextView groupname;
    @BindView(R.id.seller)
    TextView seller;
    @BindView(R.id.tv_confim_refound)
    TextView tvConfimRefound;
    @BindView(R.id.et_remark)
    TextView etRemark;
    Dialog dialog;
    SecurityCodeView securityCodeView;
    private OrderdetailEntity.OrderinfoBean orderinfo;
    private String orderid_content;
    private String realpay;
    private BandOrUnbandGuidResultDialog bandOrUnbandGuidResultDialog;
    private String handinputmoney;
    private BandOrUnbandGuidResultDialog bandOrUnbandGuidResultDialogfail;
    private OrderGetPosOrderLEntity.DataBean.ListBean data;
    private String[] content = new String[20];
    private String[] printText = new String[20];
    String dockingRefundOrderId = "";

    ProgressDialog progressDialog;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_refound_money_detail;
    }

    @Override
    protected void initBase() {
        super.initView();
        ButterKnife.bind(this);
        initDate();
        initUI();
    }

    public void initUI() {
        tvConfimRefound.setEnabled(true);

        tvTitle.setText("退款信息");
        if(data != null) {
            tvRedoundMoney.setText(data.getRealpay());
            realpay = data.getRealpay();
            realymoney.setText(realpay);
            ordermoney.setText(data.getOrdermoney());
            shopmoney.setText(data.getYouhui());
            paytime.setText(data.getPaytime());
            orderid_content = data.getOrderid();
            orderid.setText(orderid_content);
            currentshop.setText(data.getShopname());
            seller.setText(Hawk.get("sellername"));
        }
    }

    private void initDate() {
        data = (OrderGetPosOrderLEntity.DataBean.ListBean) getIntent().getSerializableExtra("date");
        if(data != null) {
            content[0] = data.getOrderid();//订单编号
            content[1] = data.getShopname();//门店
            content[2] = data.getSiteusername();//收银员
            content[3] = data.getPaytype();//支付方式
            content[4] = data.getPaystate();//支付状态
            content[5] = data.getPaytime();//支付时间
            content[6] = data.getOrdermoney();//订单金额
            content[7] = data.getRealpay();//实收金额
            content[8] = data.getRefund();//退款金额
            content[9] = data.getOrdernote();//订单备注
            content[10] = data.getRefundreason();//退款备注
            content[11] = data.getRefundtime();//退款时间
            content[12] = Hawk.get("company");//账号公司
            content[13] = data.getUseraccount();//用户账号 不一定存在
            content[14] = data.getOutorderid();//不一定存在
            content[15] = data.getSelleryouhui();//不一定存在
            content[16] = data.getYouhui();//不一定存在

        }
    }

    @OnClick({R.id.img_back, R.id.tv_confim_refound})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_confim_refound:
                //条件筛选
                handinputmoney = tvRedoundMoney.getText().toString();
                if(TextUtils.isEmpty(handinputmoney)) {
                    ToastUtils.showToast(RefoundMoneyDetailActivity.this, "退款金额不能为空");
                    return;
                }
                Double aDouble = Double.valueOf(handinputmoney);
                if(aDouble <= 0) {
                    ToastUtils.showToast(RefoundMoneyDetailActivity.this, "请输入正确的退款金额");
                    return;
                }
//                String realpay = orderinfo.getRealpay();

                Double bDouble = Double.valueOf(data.getOrdermoney());
                if(aDouble > bDouble) {//手动输入的比实际金额还有大
                    ToastUtils.showToast(RefoundMoneyDetailActivity.this,
                            "退款金额不能大于原订单金额");
                    return;
                }

                toDialogActivity(handinputmoney);
                break;
        }
    }

    private void toDialogActivity(String handinputmoney) {
        View view =
                LayoutInflater.from(RefoundMoneyDetailActivity.this).inflate(R.layout.dialog_tuikuan, null);
        // 对话框
        dialog = new Dialog(RefoundMoneyDetailActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
        //==================================弹出键盘================================================================
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //===========================================================================================================
//        InputTools.KeyBoard(et_hexiao, "open");
//        InputTools.HideKeyboard(et_hexiao);
        //findview
        //找到自定义的控件用来显示密码
        securityCodeView = (SecurityCodeView) view.findViewById(R.id.scv_edittext);
        securityCodeView.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                dialog.hide();
                LogUtils.e("getEditContent", securityCodeView.getEditContent());
                toTuikuan(RefoundMoneyDetailActivity.this,
                        securityCodeView.getEditContent(), orderid_content,
                        handinputmoney, etRemark.getText().toString());
            }

            @Override
            public void deleteContent(boolean isDelete) {
                //DO NO THING
            }
        });
    }

    public void toTuikuan(Context context, String operatePass, String orderId,
                          String remoney, String refundReason) {
        HashMap<String, String> addParams = new HashMap<>();

        //获取订单的orderID
        addParams.put("orderid", orderId);
        addParams.put("remoney", remoney);
        addParams.put("operatePass", operatePass);
        addParams.put("refundReason", refundReason);
        APIRetrofit.getAPIService().orderRefundM(RXRequest.getXingPosParams(addParams,
                context))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RefundMEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        progressDialog = new ProgressDialog(context);
                        progressDialog.setMessage("退款中...");
                        progressDialog.show();
                    }

                    @Override
                    public void onNext(RefundMEntity refundMEntity) {
                        onRefoundMoneyDetailView(refundMEntity);
                        if(progressDialog != null) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(progressDialog != null) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if(progressDialog != null) {
                            progressDialog.dismiss();
                        }
                    }
                });
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    //输入退款密码后,请求网络的结果
    @Override
    public void onRefoundMoneyDetailView(RefundMEntity refundMEntity) {
        int success = refundMEntity.getSuccess();
        if(success == 1) {
            java.text.SimpleDateFormat sdFormatter = new java.text.SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            String currentime = sdFormatter.format(curDate);
            content[11] = currentime;//退款时间
            content[8] = tvRedoundMoney.getText().toString();//退款金额
            content[10] = etRemark.getText().toString();//退款备注

            OrderRecordEntity order = new OrderRecordEntity();
            order.setMerchantName(content[12]);
            order.setOrderId(content[0]);
            if(data.getPaytype().equals("微信")) {
                order.setType(11);
            } else if(data.getPaytype().equals("支付宝")) {
                order.setType(10);
            }
            order.setOrderMoney(content[6]);
            order.setRefundMoney(content[8]);
            order.setRefundTime(content[11]);
            order.setShopName(content[1]);
            order.setCashier(content[2]);
            order.setCustomer(content[13]);
            order.setPayTime(content[5]);
            order.setRemarks(content[9]);
            order.setRefundRemarks(content[10]);
            DatabaseManager.getInstance().insert(order);


            if(refundMEntity.getData() != null && refundMEntity.getData().getDockingRefundOrderId() != null) {
                dockingRefundOrderId = refundMEntity.getData().getDockingRefundOrderId();
            }
            getOrderDetail();

//            gotosuccs();//设置过打印小票模式后退款结束不返回到订单页面 ，移到此处解决 edit by yingchuan 20200527
        } else if(success == -100 | success == -200) {
            //// TODO: 2017/12/9 0009 绑定guid  界面
            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this,
                    "autologin");
            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this,
                    "remberpassword");
            startActivity(new Intent(RefoundMoneyDetailActivity.this,
                    BangGuidActivity.class));
            finish();
        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
            //// TODO: 2017/12/9 0009 去登录的界面
            com.blankj.utilcode.util.ToastUtils.showShortSafe(refundMEntity.getErrMsg());
            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this, "autologin");
            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this,
                    "remberpassword");
            startActivity(new Intent(RefoundMoneyDetailActivity.this,
                    LoginActivity.class));
            finish();
        } else {
            //输入密码错误! 回复点击事件!!
            ToastUtils.showToast(RefoundMoneyDetailActivity.this,
                    refundMEntity.getErrMsg() + "");
            bandOrUnbandGuidResultDialogfail =
                    new BandOrUnbandGuidResultDialog(RefoundMoneyDetailActivity.this,
                            R.style.loading_dialog, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bandOrUnbandGuidResultDialogfail.dismiss();
                        }
                    }, 105);
            bandOrUnbandGuidResultDialogfail.show();
            bandOrUnbandGuidResultDialogfail.setMoney(handinputmoney);
        }
    }

    private void print(Bitmap logo, String[] content, int orderType, int printPage) {

        printOrder(logo, content, orderType, printPage);
    }

    private void printOrder(Bitmap logo, String[] content, int orderType, int printPage) {
        PrinterWrapper.printPosOrder(logo, content, orderType, printPage);
    }

    public void gotosuccs() {
        bandOrUnbandGuidResultDialog =
                new BandOrUnbandGuidResultDialog(RefoundMoneyDetailActivity.this,
                        R.style.loading_dialog, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bandOrUnbandGuidResultDialog.dismiss();
            }
        }, 104);
        bandOrUnbandGuidResultDialog.show();
        bandOrUnbandGuidResultDialog.setMoney(handinputmoney);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                RefoundMoneyDetailActivity.this.finish();
            }
        }, 3100);
    }

    private void getOrderDetail() {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", data.getOrderid());
        addParams.put("DockingRefundOrderId", dockingRefundOrderId);
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity entity) {
                        int success = entity.getSuccess();
                        if(success == 1) {
                            if(entity.getData() != null && entity.getData().size() > 0) {
                                if(entity.getData().get(0).getList().size() > 0) {
                                    data =
                                            entity.getData().get(0).getList().get(0);
                                    if(data != null) {
                                        //20200805 小票优化后使用下面的数组
                                        printText[0] = data.getOrderid();//订单编号
                                        printText[1] = data.getShopname();//门店
                                        printText[2] = data.getSiteusername();//收银员
                                        printText[3] = data.getPaytype();//支付方式
                                        printText[4] = data.getPaystate();//支付状态
                                        printText[5] = data.getPaytime();//支付时间
                                        printText[6] = data.getOrdermoney();//订单金额
                                        printText[7] = data.getRealpay();//实收金额
                                        printText[8] = data.getRefund();//退款金额
                                        printText[9] = data.getOrdernote();//订单备注
                                        printText[10] = data.getRefundreason();//退款备注
                                        printText[11] = data.getRefundtime();//退款时间
                                        printText[12] = Hawk.get("company");//账号公司
                                        printText[13] = data.getUseraccount();//用户账号 不一定存在
                                        printText[14] = data.getOutorderid();//不一定存在
                                        printText[15] = data.getSelleryouhui();//不一定存在
                                        printText[16] = data.getYouhui();//不一定存在
                                        printText[17] = Hawk.get("sellername");

                                        TransactionFlowEntity tfEntity = new TransactionFlowEntity();
                                        String json = new Gson().toJson(printText);
                                        tfEntity.setPrintType(10);
                                        tfEntity.setJson(json);
                                        DatabaseManager.getInstance().insert(tfEntity);
                                        print();

                                    }
                                }
                            }
                        }else if (success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this, "autologin");
                            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this, "remberpassword");
                            startActivity(new Intent(RefoundMoneyDetailActivity.this, BangGuidActivity.class));
                            finish();
                        } else if (success == -300|| success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(entity.getErrMsg());
                            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this, "autologin");
                            SharedPreferencesUtils.remove(RefoundMoneyDetailActivity.this, "remberpassword");
                            startActivity(new Intent(RefoundMoneyDetailActivity.this, LoginActivity.class));
                            finish();
                        } else {
                            //输入密码错误! 回复点击事件!!
                            ToastUtils.showToast(RefoundMoneyDetailActivity.this, entity.getErrMsg() + "");
                            bandOrUnbandGuidResultDialogfail = new BandOrUnbandGuidResultDialog(RefoundMoneyDetailActivity.this, R.style.loading_dialog, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    bandOrUnbandGuidResultDialogfail.dismiss();
                                }
                            }, 105);
                            bandOrUnbandGuidResultDialogfail.show();
                            bandOrUnbandGuidResultDialogfail.setMoney(handinputmoney);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                        ToastUtils.showToast(RefoundMoneyDetailActivity.this, "同步失败");
                    }

                    @Override
                    public void onComplete() {

                        ToastUtils.showToast(RefoundMoneyDetailActivity.this, "同步成功");
                    }
                });
    }


    public  void print(){
        int printPage = (int) SharedPreferencesUtils.getParam(RefoundMoneyDetailActivity.this, "printpage", 1);
        if (printPage == 0) {
            ToastUtils.showToast(RefoundMoneyDetailActivity.this, "打印张数设置为不打印,请先设置打印张数!!");
        } else {
            //显示进度条
            if (content != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if(data != null) {
                            PrinterWrapper.printMultiRefundOrderDetail(data, 0,
                                    printPage, true);
                        }
                    }
                }).start();
            }
        }
        finish();
    }

}
